var async = require("async")
var util = require("../../../util/util.js")
var shopCfg = require("../../../conf/shop.json")
var monthCardCfg = require("../../../conf/monthCard.json")
var errorLogger = require("pomelo-logger").getLogger("error-log");
module.exports = function(app) {
	return new DBRemote(app);
};

var DBRemote = function(app) {
	this.app = app
	DBRemote.app = app
    DBRemote.dbService = this.app.get("dbService")
}

var local = {}

//购买商品
DBRemote.prototype.buyGoods = function(uid,goodsId,count,cb) {
	if(!shopCfg[goodsId]){
		cb(false,"goodsId error")
		return
	}
	var needItemId = shopCfg[goodsId].needItemId
	var needValue = shopCfg[goodsId].needValue * count
	var goodsItemId = shopCfg[goodsId].goodsItemId
	var goodsValue = shopCfg[goodsId].goodsValue * count
	DBRemote.dbService.getItem(uid,needItemId,function(data) {
		// console.log("needValue ： ",needValue,"  data : ",data)
		if(data && data >= needValue){
			DBRemote.dbService.addItemReason(uid,needItemId,-needValue,"商店购买:"+goodsItemId,function(flag) {
				if(flag){
					DBRemote.dbService.addItemReason(uid,goodsItemId,goodsValue,"商店获得",function(flag) {
						cb(flag)
					})
				}else{
					errorLogger.info("buyGoods : "+uid+"   goodsId  :" + needValue)
					cb(false)
				}
			})
		}else{
			cb(false,"needValue error")
			return
		}
	})
}

//获取月卡信息
DBRemote.prototype.getMonthCardInfo = function(uid,cb) {
	DBRemote.dbService.db.hgetall("game:monthCard:"+uid,function(err,data) {
		if(err || !data){
			cb(true,{})
		}else{
			cb(true,data)
		}
	})
}

//领取每日月卡奖励
DBRemote.prototype.getMonthCardAward = function(uid,monthCardType,cb) {
	var curTime = (new Date()).getTime()
	DBRemote.dbService.db.hgetall("game:monthCard:"+uid,function(err,data) {
		var curTime = (new Date()).getTime()
		var curDate = util.getDateString()
		if(!err && data){
			if(data[monthCardType] && data[monthCardType] > curTime){
				if(!data[monthCardType+":lastTime"] || data[monthCardType+":lastTime"] != curDate){
					DBRemote.dbService.db.hset("game:monthCard:"+uid,monthCardType+":lastTime",curDate)
					var everydayAward = monthCardCfg[monthCardType].everyday
					for(var i in everydayAward){
						DBRemote.dbService.addItemReason(uid,parseInt(i),everydayAward[i],"每日月卡:"+monthCardType,function(){})
					}
					cb(true,everydayAward)
					return
				}
			}
		}
		cb(false)
		return
	})
}

//获取我的礼包信息
DBRemote.prototype.getGiftBagInfo = function(uid,cb) {
	DBRemote.dbService.db.hgetall("game:giftBag:"+uid,function(err,data) {
		if(err || !data){
			cb(true,{})
		}else{
			cb(true,data)
		}
	})
}